#include "../header/disk/disk_info.h"
#include <cjson/cJSON.h>

char*  disk_info(void)
{
    cJSON *disk_info_arr;
    FILE* mount_table;


    mount_table = NULL;
    mount_table = setmntent("/etc/mtab", "r");
    if(!mount_table)
    {
        printf("open /etc/mtab error");
        //return -1;
    }
    disk_info_arr  = cJSON_CreateArray();


    while(1)
    {
        struct statfs s;
        char *device;
        struct mntent *mount_entry;
        char *mount_point;
        mount_entry = getmntent(mount_table);
        if(!mount_entry)
        {
            endmntent(mount_table);
            break;
        }
        device = mount_entry->mnt_fsname;
        mount_point = mount_entry->mnt_dir;

        if(statfs(mount_point,&s)!=0)
        {
            printf("statfs error");
            continue;
        }
        if(s.f_blocks  > 0)
        {
            cJSON *disk_info_item;
            disk_info_item = cJSON_CreateObject();


            char block[1024] ;
            sprintf(block,"%ld",s.f_blocks);
            cJSON_AddStringToObject(disk_info_item, "blocks",block);
            //printf("blocks:%s ",block);

            char f_bfree[1024] ;
            sprintf(f_bfree,"%ld",s.f_bfree);
            cJSON_AddStringToObject(disk_info_item, "bfree",f_bfree);
            //printf("bfree:%s ",f_bfree);

            char f_bavail[1024] ;
            sprintf(f_bavail,"%ld",s.f_bavail);
            cJSON_AddStringToObject(disk_info_item, "bavail",f_bavail);
            //printf("f_bavail:%s ",f_bavail);


            char f_bsize[1024];
            sprintf(f_bsize,"%ld",s.f_bsize);
            cJSON_AddStringToObject(disk_info_item, "bsize",f_bsize);
            //printf("f_bsize:%s ",f_bsize);


            char f_ffree[1024] ;
            sprintf(f_ffree,"%ld",s.f_ffree);
            cJSON_AddStringToObject(disk_info_item, "ffree",f_ffree);
           // printf("f_ffree:%s ",f_ffree);

            cJSON_AddStringToObject(disk_info_item, "type",mount_entry->mnt_type);
            //printf("type:%s ",mount_entry->mnt_type);
            cJSON_AddStringToObject(disk_info_item, "mount_point",mount_point);
            //printf("mount_point:%s ",mount_point);
            cJSON_AddStringToObject(disk_info_item, "device",device);
           // printf("device:%s ",device);




            //disk_info_arr
            cJSON_AddItemToArray(disk_info_arr,disk_info_item);


            //cJSON_ad
            //printf("blocks:%ld,f_bavail:%ld,f_bfree:%ld,f_type:%ld,f_files:%ld,mount_point:%s,device:%s\n",s.f_blocks,s.f_bavail,s.f_bfree,s.f_type,s.f_files,mount_point,device);
        }
    }

            return cJSON_PrintUnformatted(disk_info_arr);
}
